from exception import AuthorizationException
from google.appengine.ext.webapp import RequestHandler, template
from google.appengine.ext import db
from model.token import OAuthRequestToken, OAuthAccessToken
import handler.config as config
import logging
import pickle
import tweepy

def get_app_auth_handler(url):
    return get_auth_handler(config.get_app_twitter_account(url), url)

def get_auth_handler(screen_name, url):
    app_access_token_key = db.Key.from_path('OAuthAccessToken', 
                                            screen_name)
    access_token = db.get(app_access_token_key)
    if not access_token:
        e = AuthorizationException(screen_name, 'user has not sign up')
        logging.error(e)
        raise e
    
    app_auth_handler = tweepy.OAuthHandler(
        config.get_consumer_key(url), config.get_consumer_secret(url))
    app_auth_handler.set_access_token(access_token.token_key,
                                      access_token.token_secret)
    return app_auth_handler